package cn.ljy.mes.service.impl;

import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.mes.dao.mapper.MesMaterialMapper;
import cn.ljy.mes.dao.mapper.MesMaterialTypeMapper;
import cn.ljy.mes.model.MesMaterialType;
import cn.ljy.mes.model.query.MesMaterialQuery;
import cn.ljy.mes.model.query.MesMaterialTypeQuery;
import cn.ljy.mes.service.MesMaterialTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.io.Serializable;
import java.util.List;

@Service
//@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor= MyRollBackException.class)
@Validated//表示开启sprint的校检框架，会自动扫描方法里的@Valid（@Valid注解一般写在接口即可）
@Slf4j
public class IMesMaterialTypeService extends IBaseService<MesMaterialType, MesMaterialTypeQuery> implements MesMaterialTypeService {
    @Autowired
    private MesMaterialTypeMapper mapper;
    @Autowired
    private MesMaterialMapper mesMaterialMapper;

    //设置关联属性
    private void setParam(MesMaterialType mesMaterialType){
        if(mesMaterialType!=null){
            //获取类别下的物料数量
            MesMaterialQuery materialQuery=new MesMaterialQuery();
            materialQuery.setMaterialType(mesMaterialType);
            mesMaterialType.setMaterialNumber(mesMaterialMapper.count(materialQuery));
        }
    }

    @Override
    public void afterFindAll(List<MesMaterialType> list) {
        for(MesMaterialType materialType:list){
            //添加相关关联属性
            this.setParam(materialType);
        }
    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
        for(Serializable id:ids){
            MesMaterialQuery materialQuery=new MesMaterialQuery();
            materialQuery.setMaterialType(new MesMaterialType(Long.valueOf(id.toString())));
            int materialNumber=mesMaterialMapper.count(materialQuery);
            if(materialNumber>0){
                MesMaterialType materialType=mapper.findByIdNoRelation(id);
                throw new MyServiceException("删除失败："+materialType.getName()+"下还有"+materialNumber+"个物料在使用，请先移除或转移这些物料后再执行删除");
            }
        }
    }
}
